package com.seiko.danmaku.data.repo

import android.util.Log
import com.seiko.danmaku.data.api.DanDanApi
import com.seiko.danmaku.data.api.model.MatchRequest
import com.seiko.danmaku.data.model.DanmaCommentBean
import com.seiko.danmaku.data.model.MatchResult
import com.seiko.danmaku.data.model.Result
import com.seiko.danmaku.util.MySAXParserHandler
import org.xml.sax.InputSource
import java.io.StringReader
import javax.inject.Inject
import javax.xml.parsers.SAXParserFactory


class DanDanApiRepository @Inject constructor(
    private val api: DanDanApi
) {
    private fun parseBean(xmlString: String): List<DanmaCommentBean> {
        val sAXParserFactory = SAXParserFactory.newInstance()
        val sAXParser = sAXParserFactory.newSAXParser()
        val reader = StringReader(xmlString)
        val inputSource = InputSource(reader)
        inputSource.encoding = "UTF-8"
        val myDefaultHandler = MySAXParserHandler()
        sAXParser.parse(inputSource, myDefaultHandler)

        Log.e("DANMAKU", myDefaultHandler.danmaDownloadResponse.comments.joinToString(","))
        Log.w("DANMAKU", myDefaultHandler.danmaDownloadResponse.count.toString())
        return myDefaultHandler.danmaDownloadResponse.comments

    }

    suspend fun downloadDanma(name: String, episode: String): Result<List<DanmaCommentBean>> {
        return try {
            val response = api.downloadDanma(name, episode)
            Result.Success(parseBean(response))
        } catch (e: Exception) {
            Result.Error(e)
        }
    }

    suspend fun getVideoMatchList(request: MatchRequest) : Result<Pair<Boolean, List<MatchResult>>> {
        try {
            val response = api.getVideoMatch(request)
            if (!response.success) {
                return Result.Error(Exception("(${response.errorCode}) ${response.errorMessage}"))
            }
            return Result.Success(response.isMatched to (response.matches ?: emptyList()))
        } catch (e: Exception) {
            return Result.Error(e)
        }
    }

}